<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/3/16
 * Time: 9:57
 */

namespace App\Http\Controllers\Api\V1;


use App\Logic\MessageLogic;
use App\Logic\UserBuyLogic;
use App\Models\UserBuyOrder;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UserBuyController extends BaseController
{
    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function buy(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'type' => ['required', Rule::in(['doc', 'lecture', 'channel'])],
            'id' => 'required'
        ], [
            'type.required' => '请提交购买类型',
            'id.required' => '请提交购买ID',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $type = $this->_getType($request->input("type"));
        $id = $this->getId();
        $item = UserBuyOrder::_getItem($type, $id);
        $user = $this->getUser();
        //先判断是否可以购买
        list($item_buy_state, $item_buy_message) = UserBuyOrder::_checkItemBuyState($type, $item, $user);
        if (!$item_buy_state) {
            return $this->failed($item_buy_message);
        }
        $coupons = false;
        $qd = false;
        //推广用户

        $tg_id = $this->getId('share_id', false);
        $tg_user = UserBuyLogic::getTgUser($item, $user, $tg_id);
        list($state, $order) = UserBuyOrder::createOrder($type, $item, 1, $user, $coupons, $qd, $tg_user);
        if ($state) {
            $config = $this->getWxAppPayConfig();
            $app = Factory::payment($config);
            $jssdk = $app->jssdk;
            try {
                $result = $app->order->unify([
                    'body' => '云档产品购买',
                    'out_trade_no' => $order->order_sn,
                    'total_fee' => $order->pay_money * 100,
                    'trade_type' => 'JSAPI',
                    'openid' => $user->wx_user->open_id,
                ]);
                $json = $jssdk->sdkConfig($result['prepay_id']);
                $order->pay_type = 'wx_pay';
                $order->prepay_id = $result['prepay_id'];
                $order->save();
                return $this->success($json);
            } catch (\Exception $exception) {
                return $this->failed('下单失败');
            }

        } else {
            return $this->failed('下单失败');
        }

    }

}